package cn.codingstyle.product;

import cn.codingstyle.promotion.Promotion;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ProductService {
    private final ProductRepository productRepository;
    private final ScanProductItemRepository scanProductItemRepository;
    private final PromotionRepository promotionRepository;

    public ProductService(ProductRepository productRepository,
                          ScanProductItemRepository scanProductItemRepository,
                          PromotionRepository promotionRepository) {
        this.productRepository = productRepository;
        this.scanProductItemRepository = scanProductItemRepository;
        this.promotionRepository = promotionRepository;
    }

    public void create(ProductRequest productRequest) {
        Product product = productRequest.toEntity();
        for (Integer integer : productRequest.getPromotionIds()) {
            Promotion promotion = promotionRepository.findById(integer);
            product.addPromotion(promotion);
        }
        productRepository.save(product);
    }

    public ProductReceipt scan(String barcode, Integer quantity) {
        Product product = productRepository.findByBarcode(barcode);
        ProductItem productItem = new ProductItem(product, quantity);
        scanProductItemRepository.add(productItem);
        return new ProductReceipt(scanProductItemRepository.findAll());
    }
}
